'use client';

import type { ISectionClient } from '@/interfaces';
import Image from 'next/image';
import classNames from 'classnames';
import classs from './section.module.scss';
import Link from 'next/link';
import { getCover, getUserAvatar } from '@/lib/tool';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import type { ISectionPageContext } from '@/contexts/section';
import { SectionPageContext } from '@/contexts/section';
import { useContext } from 'react';
import { AppContext } from '@/contexts/app';
import PcBox from '@/app/[locale]/common/other/pc';
import SectionH5Page from '@/app/[locale]/sections/h5';
import H5Box from '@/app/[locale]/common/other/h5';

export default function SectionPage({
  source,
  translatedFields,
}: ISectionPageContext) {
  const sections = source.sections;
  const defaultSgKey = '0_0';
  const data = sections.reduce(
    (previousValue, currentValue) => {
      if (currentValue.sectionGroup) {
        const id =
          currentValue.sectionGroup.id + '_' + currentValue.sectionGroup.sort;
        if (id in previousValue) {
          previousValue[id].push(currentValue);
        } else {
          previousValue[id] = [currentValue];
        }
      } else {
        previousValue[defaultSgKey].push(currentValue);
      }
      return previousValue;
    },
    { [defaultSgKey]: [] } as {
      [id: string]: ISectionClient[];
    },
  );

  return (
    <SectionPageContext.Provider value={{ source, translatedFields }}>
      <PcBox classs="col px-2 py-4">
        <div className="card border-0">
          <div className="card-body py-4">
            {sections.length > 0 ? (
              <div className="row gap-5">
                {Object.keys(data).length === 1 ? (
                  <div className="col-12">
                    <div className={classNames(classs.box)}>
                      {data[defaultSgKey].map((item) => {
                        return <SectionItem key={item.id} item={item} />;
                      })}
                    </div>
                  </div>
                ) : (
                  <>
                    {Object.keys(data)
                      .sort((a, b) =>
                        a === defaultSgKey || b === defaultSgKey
                          ? -1
                          : parseInt(b.split('_')[1]) -
                            parseInt(a.split('_')[1]),
                      )
                      .filter((key) => data[key].length > 0)
                      .map((key) => {
                        return (
                          <div key={key} className="col-12">
                            <div className="mb-4 d-flex justify-content-between">
                              <div className="h4">
                                {key === defaultSgKey
                                  ? translatedFields.otherContent
                                  : data[key][0].sectionGroup?.name}
                              </div>
                              <div>
                                <i className="bi bi-arrow-right fs-4"></i>
                              </div>
                            </div>
                            <div className={classNames(classs.box)}>
                              {data[key].map((item) => {
                                return (
                                  <SectionItem key={item.id} item={item} />
                                );
                              })}
                            </div>
                          </div>
                        );
                      })}
                  </>
                )}
              </div>
            ) : (
              <Nodata isVh100 />
            )}
          </div>
        </div>
      </PcBox>

      <H5Box classs="col px-2 py-4">
        <SectionH5Page />
      </H5Box>
    </SectionPageContext.Provider>
  );
}

const SectionItem = ({ item }: { item: ISectionClient }) => {
  const { translatedFields } = useContext(SectionPageContext)!;
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata.env;

  return (
    <div className={classNames('card border-0 rounded', classs.item)}>
      <div className="card-body">
        {item.cover && (
          <div className="position-relative overflow-hidden">
            <Image
              className="rounded w-100 h-auto object-fit-cover"
              src={getCover(item.cover, metadata)}
              alt={item.name}
              title={item.name}
              placeholder="blur"
              blurDataURL={env.APP_BLUR_DATA_URL}
              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
              fill
            />
          </div>
        )}

        <div className="container">
          {item.admins.length > 0 && (
            <div
              className="my-4 position-relative w-100"
              style={{ height: 48 }}
            >
              {item.admins.slice(0, 5).map((item, index) => {
                return (
                  <div
                    key={item.id}
                    className="position-absolute"
                    style={{
                      left: index * 33,
                      zIndex: index + 1,
                    }}
                  >
                    <Link
                      title={`${item.alias}(${item.id})`}
                      className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
                      href={`/users/${item.id}`}
                    >
                      <Image
                        className="rounded-circle"
                        src={getUserAvatar(item, metadata).smallAvatarUrl}
                        alt="avatar"
                        title={
                          item.alias ? `${item.alias} (ID. ${item.id})` : ''
                        }
                        placeholder="blur"
                        blurDataURL={env.APP_BLUR_DATA_URL}
                        width={48}
                        height={48}
                      />
                    </Link>
                  </div>
                );
              })}
              {item.admins.length > 5 && (
                <div
                  className="position-absolute fs-5 link-secondary"
                  style={{ left: 198, top: 6 }}
                >
                  <Link
                    className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
                    href={`/sections/${item.id}`}
                  >
                    +{item.admins.length - 5}
                  </Link>
                </div>
              )}
            </div>
          )}

          <p className="h5 my-4">
            <Link
              href={`/sections/${item.id}`}
              className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
            >
              {item.name}
            </Link>
          </p>

          {item.overview && (
            <p
              className="text-wrap text-truncate yw-line-clamp-3 text-secondary"
              dangerouslySetInnerHTML={{
                __html: item.overview,
              }}
            ></p>
          )}

          <p>
            <Link
              href={`/sections/${item.id}`}
              className="text-decoration-none position-relative"
            >
              {translatedFields.enterContent}
              <i
                className="bi bi-arrow-up-short align-middle d-inline-block fs-4"
                style={{ transform: 'rotate(45deg)' }}
              ></i>
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
};
